﻿<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>简单的模块滑动效果</title>
<!--autor: carriehuang | QQ:453555909 | 转载需注明原处-->
<head>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        body{
            position: relative;
        }
        .box{
            width:50px;
            height:50px;
            background-color: #990000;
            position: absolute;
            left: 0;
            top:40px;
        }
    </style>
</head>
<body>


<script type="text/javascript">

    window.onload=function(){
        var str = '';
        var len = 20;
        var num = 0;
        var timer = null;
        var onOff = true;
        var arrBox = document.getElementsByTagName("div");
        for(var i=0;i<len;i++){
            str = '<div class="box"></div>';
            document.body.innerHTML += str;
            arrBox[i].style.left = i*60+"px";
        };

        document.onclick = function(){
            timer = setInterval(function(){
                if(onOff){
                    doMove(arrBox[num],"top",30,500);
                    num++;
                    if(num==len){
                        clearInterval(timer);
                        onOff = false;
                    }
                }else{
                    num--;
                    doMove(arrBox[num],"top",30,10);
                    if(num==0){
                        clearInterval(timer);
                        onOff = true;
                    }
                }

            },100);



        };

        /*
        * obj 元素对象
        * attr 属性
        * dir 速度
        * target 终点
        * */
        function doMove(obj,attr,dir,target){
            dir = parseInt(getStyle(obj,attr))<target?dir:-dir;
            clearInterval(obj.timer);
            obj.timer = setInterval(function(){
                var speed =  parseInt(getStyle(obj,attr))+dir;
                if(speed > target && dir>0 || speed < target && dir<0){
                    speed = target;
                }
                if(speed==target){
                    clearInterval(obj.timer);
                }
                obj.style[attr] = speed+"px";

               // console.log( obj.style[attr]);
            },100);
        };
        //判断浏览器，实现获取样式表样式属性的兼容
        function getStyle(obj,attr){
            return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];
        }
    }
</script>
</body>

</html>
